import React, { Component, PropTypes } from 'react';
import { Upload, message, Checkbox, Button, Icon } from 'antd';
import { connect } from 'dva';
import dataEditCreate from '../DataEdit'
import * as datetime from '../../../utils/datetime'
class Step1 extends React.Component {
    constructor(props) {
        super(props);
        this.state = {

        };
    }
    beforeUpload(file) {
        // console.log(file.type)
        // const isExcel = file.type === "application/vnd.ms-excel" || file.type === "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        // if (!isExcel) {
        //     message.error('请选择excel文件!');
        //     return false
        // }
        const isXlsx = file.name.lastIndexOf(".xlsx") !== -1;
        if (!isXlsx) {
            message.error('系统仅支持xlsx文件格式，请转换后再导入!',5);
            return false
        }
        const isLt100M = file.size / 1024 / 1024 < 100;
        if (!isLt100M) {
            message.error('文件不能大于100MB!',5);
            return false
        }
        return true;
    }
    handleUploadChange(info) {
        if (info.file.status === 'done') {
            const { sheetNames, fileName, dataMap } = info.file.response;
            const daoName = this.props.daoName
            this.props.dispatch({
                type: `${daoName}_DataImport/setUplodFile`,
                payload: { fileName, sheetNames, dataMap }
            });
            message.success(`${info.file.name} 文件上传成功！`);
        } else if (info.file.status === 'error') {
            message.error(`${info.file.name} 文件上传失败！`,5);
        }
    }
    handleCheckChange(e) {
        const checked = e.target.checked;
        const daoName = this.props.daoName
        this.props.dispatch({
            type: `${daoName}_DataImport/setHasColHeader`,
            payload: { hasColHeader: checked }
        });
    }
    getFormData() {
        const form = this.refs.form1.getForm()
        let formData = null;
        form.validateFields((err, values) => {
            if (!err) {
                formData = { ...values };
                this.props.controls.map((c, i) => {
                    if (this.props.paramNames.findIndex(name =>  name === c.name ) != -1) {
                        if ((c.type === "date" || c.type === "datetime")) {
                            if (c.dataType === "date" || c.dataType === "datetime") {
                                let date = !values[c.name] ? null : new Date(values[c.name])
                                formData[c.name] = !values[c.name] ? null : new Date(date.getFullYear(), date.getMonth(), date.getDate(), 8, 0, 0)
                            } 
                            else {
                                const dval = new Date(values[c.name])
                                formData[c.name] = datetime.format(dval, "yyyyMMdd")
                            }
                        }else if (c.type === "month"){
                            const dval = new Date(values[c.name])
                            formData[c.name] = datetime.format(dval, "yyyyMM")
                        }
                    }
                })
            }
        })
       
        return formData
    }
    render() {
        let controls = []
        const clen = this.props.controls.length
        this.props.paramNames.map((p) => {
            for (let i = 0; i < clen; i++) {
                if (this.props.controls[i].name === p) {
                    let cont = { ...this.props.controls[i] };
                    cont.grid = 24 / 24;
                    controls.push(cont)
                }
            }
        })
        let selSheet = { type: "select", grid: 24 / 24, required: true, data: this.props.sheetNames, name: "select_sheetName", label: "选择表单" }
        controls.push(selSheet)
        const { daoName, modelName, importName } = this.props
        const props = {
            name: importName,
            action: `/api/Upload/${importName}`,
            onChange: this.handleUploadChange.bind(this),
            beforeUpload: this.beforeUpload,
            accept: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            multiple: false,
        };
        const EditForm = dataEditCreate(modelName);
        return (<div style={{ display: this.props.visible ? "block" : "none" }}>
            <div style={{ paddingLeft: "92px" }}>
                <Upload {...props}>
                    <Button>
                        <Icon type="upload" /> 选择文件
                    </Button>
                </Upload>
            </div>
            <div style={{ paddingTop: 25 }}>
                <EditForm ref="form1" daoName={daoName} controls={controls} record={this.props.params} selectFirst={false} />
            </div>
            <div style={{ paddingLeft: "92px", display: "none"}}>
                <Checkbox checked={this.props.hasColHeader} onChange={this.handleCheckChange.bind(this)}>
                    第一行包含列名(推荐)
                </Checkbox>
                <p>{this.props.hasColHeader ? "说明：第一行为列名，从第二行开始为数据" : "说明：数据从第一行开始，没有列名"}</p>
            </div>
        </div >)
    }
}
Step1.propTypes = {
    importName: PropTypes.string,
    modelName: PropTypes.string,
    daoName: PropTypes.string,
    controls: PropTypes.array,
    paramNames: PropTypes.array,
    visible: PropTypes.bool
}
Step1.defaultProps = {
    importName: "",
    daoName: "",
    controls: [],
    paramNames: [],
    visible: false
}
export default function step1Create(daoName) {
    function mapStateToProps(state, props) {
        const modelName = props.modelName ? props.modelName : daoName
        const dimodel = `${daoName}_DataImport`
        const { hasColHeader, fileName, sheetNames, params } = state[dimodel];
        return {
            hasColHeader, fileName, sheetNames, params, modelName
        }
    }
    return connect(mapStateToProps, null, null, { withRef: true })(Step1);
}
